﻿Type.registerNamespace('spdevlab.fieldSamples');

spdevlab.fieldSamples.AutoUploadImageField = spdevlab.fieldSamples.AutoUploadImageField || function () {

    var self = this;

    spdevlab.fieldSamples.AutoUploadImageField.instances = [];

    spdevlab.fieldSamples.AutoUploadImageField.prototype._fieldName = "";
    spdevlab.fieldSamples.AutoUploadImageField.prototype._selectedImageUrl = "";

    spdevlab.fieldSamples.AutoUploadImageField.prototype._imageUploadFileControlId = "";
    spdevlab.fieldSamples.AutoUploadImageField.prototype._imagePreviewControlId = "";
    spdevlab.fieldSamples.AutoUploadImageField.prototype._imageFileUploadUrlControlId = "";

    spdevlab.fieldSamples.AutoUploadImageField.onFileControlChanged = function (instanceId) {

        var currentInstance = spdevlab.fieldSamples.AutoUploadImageField.instances[instanceId];

        // TODO
        if (currentInstance) {
            currentInstance._uploadFile();
        }
        else {
            alert('Err: [Cannot find instance with id:[' + instanceId + ']');
        }
    }

    // cool stuff form uploading files by 
    // http://www.shillier.com/archive/2013/03/26/uploading-files-in-sharepoint-2013-using-csom-and-rest.aspx
    spdevlab.fieldSamples.AutoUploadImageField.prototype._uploadFile = function () {

        var imageSourceControl = document.getElementById(self._imageUploadFileControlId);

        if (imageSourceControl.files.length === 0) {
            return;
        }

        // TODO
        var parts = imageSourceControl.value.split("\\");

        var filename = parts[parts.length - 1];
        var fileTimestamp = new Date().getTime();
        // add timestamp
        var filenameParts = filename.split(".");

        if (filenameParts.length > 1) {
            var fileExtension = filenameParts.pop();
            filenameParts.push(fileTimestamp);
            filenameParts.push(fileExtension);
        }
        else {
            filenameParts.push(fileTimestamp);
        }

        filename = filenameParts.join(".");

        var file = imageSourceControl.files[0];

        var reader = new FileReader();

        var waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Image is being uploaded...', 'Please wait while your image is being uploaded...');

        reader.onload = function (e) {

            var buffer = e.target.result;

            var bytes = new Uint8Array(buffer);
            var content = new SP.Base64EncodedByteArray();

            for (var b = 0; b < bytes.length; b++)
                content.append(bytes[b]);

            // TODO
            var serverRelativeUrl = _spPageContextInfo.siteServerRelativeUrl + "/SiteCollectionImages";
            var ctx = new SP.ClientContext.get_current();

            var createInfo = new SP.FileCreationInformation();

            createInfo.set_content(content);
            createInfo.set_overwrite(true);
            createInfo.set_url(filename);

            var files = ctx.get_site().get_rootWeb().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
            ctx.load(files);

            files.add(createInfo);

            ctx.executeQueryAsync(
                Function.createDelegate(this, function () {

                    // TODO
                    var t = window.setInterval(
                        function () {

                            var fileLink = serverRelativeUrl + "/" + filename;

                            document.getElementById(self._imageFileUploadUrlControlId).innerHTML = "<a target='_blank' href='" + fileLink + "' >" + fileLink + "</a>";

                            window.clearInterval(t);

                            var filePreview = document.getElementById(self._imagePreviewControlId);

                            filePreview.style.display = '';
                            filePreview.src = fileLink + "?height=100";

                            self._selectedImageUrl = fileLink + ", " + filename;
                            waitDialog.close();
                        }, 2500
                    );
                }),
                Function.createDelegate(this, function (sender, args) {
                    waitDialog.close();
                    alert("Error while uploading image... " + args.get_message());
                }));
        }

        reader.readAsArrayBuffer(file);

    };

    spdevlab.fieldSamples.AutoUploadImageField.prototype._viewTemplate = function (renderCtx, field, listItem, listSchema) {

        // TODO
        var currentVal = '(null)';

        if (renderCtx != null && renderCtx.CurrentItem != null)
            currentVal = eval('renderCtx.CurrentItem.' + field.Name);

        var parts = currentVal.toString().split(',');

        var url = parts[0];
        var description = parts[1];

        var result = "";

        if (url !== '' && url !== null)
            result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
        else
            result += "<div><img width='96' height='96' src='' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

        return result;
    }

    spdevlab.fieldSamples.AutoUploadImageField.prototype._displayFormTemplate = function (ctx) {

        if (ctx == null || ctx.CurrentFieldValue == null)
            return '';

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

        if (formCtx == null || formCtx.fieldSchema == null)
            return '';

        formCtx.registerGetValueCallback(formCtx.fieldName, function () {
            return spdevlab.fieldSamples.AutoUploadImageField._selectedImageUrl;
        });

        var parts = ctx.CurrentFieldValue.toString().split(',');

        var url = parts[0];
        var description = parts[1];

        var result = "";

        // TODO
        if (url !== '' && url !== null)
            result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
        else
            result += "<div><img width='96' height='96' src='' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

        return result;
    }

    spdevlab.fieldSamples.AutoUploadImageField.prototype._newFormTemplate = function (ctx) {

        if (ctx == null || ctx.CurrentFieldValue == null)
            return '';

        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

        if (formCtx == null || formCtx.fieldSchema == null)
            return '';

        formCtx.registerGetValueCallback(formCtx.fieldName, function () {
            return self._selectedImageUrl;
        });

        var parts = ctx.CurrentFieldValue.toString().split(',');

        var url = parts[0];
        var description = parts[1];

        // TODO
        var result = "";

        result += "<div id='uploadFileExperience' style='padding:10px; border:1px #dedede solid'>";
        result += "Select image file: <input onchange=\"javascript:spdevlab.fieldSamples.AutoUploadImageField.onFileControlChanged('" + self._fieldName + "');\" type='file' id='" + self._imageUploadFileControlId + "'><br/>";

        if (url !== '' && url !== null)
            result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
        else
            result += "<div><img width='96' height='96' src='' id='" + self._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

        var imageLink = "<a target='_blank' href='" + url + "' >" + url + "</a>";

        result += "<div id='" + self._imageFileUploadUrlControlId + "'>" + imageLink + "</div>";
        result += "</div>";

        self._selectedImageUrl = url + ", " + description;

        return result;
    };

    spdevlab.fieldSamples.AutoUploadImageField.prototype.init = function (targetFieldName) {

        self._fieldName = targetFieldName;

        self._imageUploadFileControlId = "spdevlab_imageFileUploadControl_" + self._fieldName;
        self._imagePreviewControlId = "spdevlab_imagePreviewControl_" + self._fieldName;
        self._imageFileUploadUrlControlId = "spdevlab_imageUrlControl_" + self._fieldName;

        spdevlab.fieldSamples.AutoUploadImageField.instances[self._fieldName] = self;

        var fieldName = self._fieldName;

        var fieldTemplates = {};

        fieldTemplates["Templates"] = {};
        fieldTemplates.Templates["Fields"] = {};

        fieldTemplates.Templates.Fields[fieldName] = {};

        fieldTemplates.Templates.Fields[fieldName]["View"] = self._viewTemplate;
        fieldTemplates.Templates.Fields[fieldName]["NewForm"] = self._newFormTemplate;
        fieldTemplates.Templates.Fields[fieldName]["EditForm"] = self._newFormTemplate;
        fieldTemplates.Templates.Fields[fieldName]["DisplayForm"] = self._displayFormTemplate;

        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldTemplates);
    }
};

(function () {
    var autoUploadImageField = new spdevlab.fieldSamples.AutoUploadImageField();
    autoUploadImageField.init("AutoUploadImageField");
})();